package vip.liux.backend.adapter.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vip.liux.application.dots.PagedResultDto;
import vip.liux.application.dots.PagedResultRequestDto;
import vip.liux.backend.application.service.pay.PayDemoOrderService;
import vip.liux.backend.application.service.pay.dto.notify.PayNotifyResp;
import vip.liux.backend.application.service.pay.dto.notify.PayOrderNotifyDto;
import vip.liux.backend.application.service.pay.dto.notify.PayRefundNotifyDto;
import vip.liux.contracts.models.pay.PayDemoOrder;
import vip.liux.core.current.ICurrentUser;

import static vip.liux.backend.infrastructure.utils.ServletUtil.getClientIP;

/**
 * 示例订单管理 Controller
 *
 * <p>提供示例订单的创建、查询、支付、退款等接口</p>
 *
 * @author liuxinhh
 */
@RestController
@RequestMapping("/api/pay/demo/order")
public class PayDemoOrderController {

    @Autowired
    private PayDemoOrderService payDemoOrderService;

    @Autowired
    private ICurrentUser<Long> currentUser;

    /**
     * 创建示例订单
     *
     * @param spuId 商品编号
     * @return 订单编号
     */
    @PostMapping("/submit")
    public Long createDemoOrder(@RequestParam("spuId") Long spuId) {
        return payDemoOrderService.createDemoOrder(currentUser.getId(), spuId);
    }

    /**
     * 查询示例订单详情
     *
     * @param id 订单编号
     * @return 示例订单
     */
    @GetMapping("/{id}")
    public PayDemoOrder getDemoOrder(@PathVariable("id") Long id) {
        return payDemoOrderService.getDemoOrder(id);
    }

    /**
     * 分页查询示例订单
     *
     * @param pageReqVO 分页请求参数
     * @return 分页结果
     */
    @GetMapping("/page")
    public PagedResultDto<PayDemoOrder> getDemoOrderPage(PagedResultRequestDto pageReqVO) {
        return payDemoOrderService.getDemoOrderPage(pageReqVO);
    }

    /**
     * 更新示例订单为已支付
     */
    @PostMapping("/paid")
    public PayNotifyResp updateDemoOrderPaid(@RequestBody PayOrderNotifyDto input) {
        payDemoOrderService.updateDemoOrderPaid(Long.valueOf(input.getMerchantOrderId()), input.getPayOrderNo());
        return new PayNotifyResp("success", 0);
    }

    /**
     * 发起示例订单退款
     *
     * @param id 订单编号
     */
    @PostMapping("/refund")
    public void refundDemoOrder(@RequestParam("id") Long id) {
        payDemoOrderService.refundDemoOrder(id, getClientIP());
    }

    /**
     * 更新示例订单为已退款
     */
    @PostMapping("/refunded")
    public PayNotifyResp updateDemoOrderRefunded(@RequestBody PayRefundNotifyDto input) {
        payDemoOrderService.updateDemoOrderRefunded(
                Long.valueOf(input.getMerchantOrderId()),
                input.getMerchantRefundId(),
                input.getPayRefundNo());
        return new PayNotifyResp("success", 0);
    }
}